<template>
  <div class="com-container">
    <div class="com-chart" ref="foreign"></div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name: "Foreign_Country",
  data() {
    return {
      mychart: null,
      allData: null, //服务器返回的数据
    };
  },
  created() {
    //在组件创建完成之后进行回调函数的注册
    this.$socket.registerCallBack('foreginData',this.getData)
  },
  mounted() {
    this.initChart();
    //this.getData();
    //发送数据给服务器，对服务器请求数据
    this.$socket.send({
      action: 'getData',
      socketType: 'foreginData',
      chartName: 'foregin_country',
      value: ''
    })
    window.addEventListener("resize", this.screenAdapter);
    //在页面加载完成的时候，主动进行屏幕的适配
    this.screenAdapter()
  },
  destroyed() {
    window.removeEventListener('resize',this.screenAdapter)
    //在组件销毁之后进行回调函数的取消
    this.$socket.unRegisterCallBack('foreginData')
  },
  methods: {
    initChart() {
      this.mychart = this.$echarts.init(this.$refs.foreign, this.theme);
      const initOption = {
        title: {
          text: '▎国外用户分布情况',
          left: 20,
          top: 20,
        },
        grid: {
          top: '20%',
          left: '3%',
          right: '6%',
          bottom: '3%',
          containLabel: true,//距离是包含坐标轴上的文字
        },
        tooltip: {
          trigger: "axis",
        },
        xAxis: {
          type: "category",
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            type: "line",
            markLine: {
                data: [
                    {type: 'max', name: '最大值'}
                ]
            }
          },
        ],
      }
      this.mychart.setOption(initOption)
    },
    //ret是服务器发送给客户端的图表数据
    getData(ret) {
      //const { data: ret } = await this.$http.get("foregin_country");
      console.log(ret, "foregin_country");
      this.allData = ret;
      this.updateChart();
    },
    updateChart() {
      const xdata = this.allData.map((item) => {
        return item.county;
      });
      const ydata = this.allData.map((item) => {
        return item.rate;
      });
      const dataOption = {
        xAxis: {data: xdata,},
        series: [{data: ydata,},],
      };
      this.mychart.setOption(dataOption);
    },
    //当浏览器的大小发生变化时，调用该方法，完成屏幕的适配
    screenAdapter() {
      const titleFontSize = (this.$refs.foreign.offsetWidth / 100) * 3.6;
      const adapterOption = {
        title: {
          textStyle: {fontSize: titleFontSize,},
        },
      };
      this.mychart.setOption(adapterOption);
      //手动调用图表对象的resize
      this.mychart.resize();
    },
  },
  computed: {
    ...mapState(['theme'])
  },
  watch: {
    theme() {
      this.mychart.dispose()//销毁当前图表
      this.initChart()//重新以最新主题初始化图表对象
      this.screenAdapter()
      this.updateChart()
    }
  },
};
</script>

<style>
</style>